package com.wt.chat.service.impl;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.entity.Kefu;
import com.wt.chat.exception.BaseException;
import com.wt.chat.mapper.KefuMapper;
import com.wt.chat.model.KefuModel;
import com.wt.chat.request.LoginRequest;
import com.wt.chat.service.LoginService;
import com.wt.chat.utils.Keys;
import com.wt.chat.utils.RSACoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

import com.wt.chat.mapper.KefuMapper;

/**
 * @description
 * @author: wangtao
 * @date:15:03 2019/11/8
 * @email:taow02@jumei.com
 */
@Service
public class LoginServiceImpl implements LoginService {

	private final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private KefuMapper kefuMapper;

	@Override
	public String generateNonceStr() {
		String nonceStr = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
		redisCache.set(nonceStr, nonceStr, 60);
		return nonceStr;
	}

	public void checkLogin(LoginRequest loginRequest) {
		String token = loginRequest.getToken();
		String nonceStr = "";
		String redisNonceStr = "";
		try {
			token = RSACoder.decryptByPrivateKey(token, RSACoder.RSA_PRIVATE_KEY);
			nonceStr = token.substring(token.length() - 5);
			redisNonceStr = redisCache.get(nonceStr, String.class);
			redisCache.del(nonceStr);
		} catch (Exception e) {
			throw new BaseException("密码解密失败");
		}
		if (StringUtils.isEmpty(redisNonceStr) || !nonceStr.equals(redisNonceStr)) {
			throw new BaseException("非法请求");
		}
		loginRequest.setToken(token.substring(0, token.length() - 5));
	}

	@Override
	public void doLogin(LoginRequest loginRequest) {
		Kefu kefu = kefuMapper.findByUsername(loginRequest.getUsername());
		//返回用户信息为NULL时统一处理成:用户或密码错误
		if (kefu == null) {
			// 用户或密码错误相关业务
//			throw new BaseException("用户或密码错误!!");
		}
		// 加入上线缓存
		KefuModel cacheKefu = redisCache.hget(Keys.KEFU_ONLINE_HASH_KEY, kefu.getId() + "", KefuModel.class);
		if(cacheKefu == null) {
			redisCache.hset(Keys.KEFU_ONLINE_HASH_KEY, kefu.getId() + "", kefu);
		}
	}

}
